package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CodeEnum;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录请求
     *
     * @param request  保存session数据
     * @param employee 从前端获取的员工信息
     * @return 统一返回R对象包装数据
     */
    @PostMapping("/login")
    public R<String> login(HttpServletRequest request, @RequestBody Employee employee) {
        return employeeService.login(request, employee);
    }

    /**
     * 员工退出功能
     *
     * @param request 清理页面session
     * @return 返回结果
     */
    @PostMapping("/logout")
    public R<String> loginOut(HttpServletRequest request) {
        employeeService.loginOut(request);
        return R.success("退出成功");
    }

    @PostMapping
    public R<String> saveEmployee(HttpServletRequest httpServletRequest, @RequestBody Employee employee) {
        return employeeService.saveEmployee(httpServletRequest, employee);
    }

    /**
     * 员工信息查询
     *
     * @param page     第几页
     * @param pageSize 查几条数据
     * @param name     是否查名字
     * @return 分页数据
     */
    @GetMapping("/page")
    public R<Page<Employee>> pageEmployee(int page, int pageSize, String name) {

        return employeeService.pageEmployee(page, pageSize, name);
    }

    @PutMapping()
    public R changeStatus(@RequestBody Employee employee, HttpServletRequest request) {
        if(employee.getId() == 1 && !("admin").equals(employee.getUsername())){
            return R.error("管理员用户不能修改账号");
        }
        if(employee.getId() == 1 && !employee.getName().equals("管理员")){
            return R.error("管理员用户不能修改用户名");
        }
        int status = employeeService.changeStatus(employee, request);
        if (status == CodeEnum.ENTITY_IS_DELETE){
            return R.error("用户已被删除");
        }
        if (status == CodeEnum.ENTITY_IS_ADMIN){
            return R.error("管理员不能被删除");
        }
        return R.success("更新成功");
    }
    @GetMapping("/{id}")
    public R<Employee> updateEmpById(@PathVariable Long id){
        Employee employee = employeeService.getEmpById(id);
        if(employee == null){
            return R.error("用户为空");
        }
        return R.success(employee);
    }
}
